<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      :border="false"
      title="创建订单"
      fixed
      left-icon="back"
      @clickLeft="goBack"
    />
    <view class="content">
      <!-- 基本信息组 -->
      <view class="form-section">
        <!-- 支付金额 -->
        <view class="form-item inline-item border-bottom">
          <view class="form-label-wrapper">
            <text class="required-icon">*</text>
            <text class="form-label">支付金额</text>
          </view>
          <view class="amount-input-wrapper-inline">
            <text class="currency">¥</text>
            <input
              class="amount-input-inline"
              type="digit"
              v-model="paymentAmount"
              placeholder="请输入支付金额"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>

        <!-- 让利比例 -->
        <view class="form-item border-bottom" @click="showPointsRatioSelector">
          <view class="form-label-wrapper">
            <text class="required-icon">*</text>
            <text class="form-label">让利比例</text>
          </view>
          <view class="form-value">
            <text>{{ pointsRatio }}%</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 支付方式 -->
        <view class="form-item border-bottom" @click="showPayWaySelector">
          <view class="form-label-wrapper">
            <text class="required-icon">*</text>
            <text class="form-label">支付方式</text>
          </view>
          <view class="form-value">
            <text>{{ payWayText }}</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 用户手机号 -->
        <view class="form-item inline-item">
          <view class="form-label-wrapper">
            <text class="required-icon">*</text>
            <text class="form-label">用户手机号</text>
          </view>
          <input
            class="form-input-inline"
            type="text"
            v-model="memberPhone"
            placeholder="请输入用户手机号"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <!-- 上传材料组 -->
      <view class="form-section upload-group">
        <!-- 有无发票 -->
        <view class="section-header-simple">
          <text class="section-title">有无发票</text>
        </view>
        <view class="radio-group">
          <view
            class="radio-item"
            :class="{ active: hasInvoice === true }"
            @click="hasInvoice = true"
          >
            <view class="radio-icon">
              <view v-if="hasInvoice === true" class="radio-dot"></view>
            </view>
            <text class="radio-label">有</text>
          </view>
          <view
            class="radio-item"
            :class="{ active: hasInvoice === false }"
            @click="hasInvoice = false"
          >
            <view class="radio-icon">
              <view v-if="hasInvoice === false" class="radio-dot"></view>
            </view>
            <text class="radio-label">无</text>
          </view>
        </view>

        <!-- 买卖双方合同上传 -->
        <view class="upload-item">
          <view class="section-header">
            <text class="required-icon">*</text>
            <text class="section-title">买卖双方合同上传</text>
          </view>
          <UploadMedia
            v-model="contractFiles"
            upload-type="image"
            :max-count="1"
            :max-size="5"
            upload-text="选择图片"
            tip-text="图片仅支持jpg、png格式，大小不可超过5M，最多1张"
          />
        </view>

        <!-- 买方付款凭证上传 -->
        <view class="upload-item">
          <view class="section-header">
            <text class="required-icon">*</text>
            <text class="section-title">买方付款凭证上传</text>
          </view>
          <UploadMedia
            v-model="paymentVoucherFiles"
            upload-type="image"
            :max-count="1"
            :max-size="5"
            upload-text="选择图片"
            tip-text="图片仅支持jpg、png格式，大小不可超过5M，最多1张"
          />
        </view>

        <!-- 买卖双方发票上传 -->
        <view class="upload-item">
          <view class="section-header">
            <text class="required-icon">*</text>
            <text class="section-title">买卖双方发票上传</text>
            <text class="warning-text">（伪造发票，p图篡改违法行为）</text>
          </view>
          <UploadMedia
            v-model="invoiceFiles"
            upload-type="image"
            :max-count="1"
            :max-size="5"
            upload-text="选择图片"
            tip-text="图片仅支持jpg、png格式，大小不可超过5M，最多1张"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view
        class="submit-button"
        :class="{ disabled: submitting }"
        @click="handleSubmit"
      >
        <text>{{ submitting ? "提交中..." : "提交订单，前往汇款" }}</text>
      </view>
    </view>

    <!-- 让利比例选择器 -->
    <uni-popup ref="pointsRatioSelectorRef" type="bottom">
      <view class="ratio-picker-modal">
        <view class="picker-header">
          <text class="picker-cancel" @click="closePointsRatioSelector"
            >取消</text
          >
          <text class="picker-title">让利比例</text>
          <text class="picker-confirm" @click="confirmPointsRatio">确定</text>
        </view>

        <picker-view
          class="picker-view"
          :value="pickerValue"
          @change="pickerChange"
          :indicator-style="indicatorStyle"
        >
          <picker-view-column>
            <view
              v-for="(ratio, index) in pointsRatioList"
              :key="index"
              class="picker-item"
            >
              {{ ratio }}%
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>

    <!-- 支付方式选择器 -->
    <uni-popup ref="payWaySelectorRef" type="bottom">
      <view class="pay-way-selector">
        <view class="selector-header">
          <text class="selector-cancel" @click="closePayWaySelector">取消</text>
          <text class="selector-title">选择支付方式</text>
          <text class="selector-confirm" @click="confirmPayWay">确定</text>
        </view>
        <scroll-view class="pay-way-list" scroll-y>
          <view
            v-for="item in payWayList"
            :key="item.value"
            class="pay-way-item"
            :class="{ active: tempPayWay === item.value }"
            @click="tempPayWay = item.value"
          >
            <text class="pay-way-name">{{ item.label }}</text>
            <uni-icons
              v-if="tempPayWay === item.value"
              type="checkmarkempty"
              size="20"
              color="#fabc02"
            ></uni-icons>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRequest } from "ahooks-vue";
import UploadMedia from "@/components/UploadMedia/UploadMedia.vue";
import { createBigReceiptOrder } from "@/api/mine";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import { encryptApi } from "@/api";
import rsa from "@/utils/rsa";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

// 页面加载时恢复 store 数据
onMounted(() => {
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  console.log("商户ID:", storeStore.storeId);
  console.log("用户ID:", userStore.userId);
});

// 支付金额
const paymentAmount = ref("");

// 让利比例
const pointsRatio = ref(3);

// 用户手机号
const memberPhone = ref("");

// 有无发票
const hasInvoice = ref(true);

// 买卖双方合同文件
const contractFiles = ref([]);

// 买方付款凭证文件
const paymentVoucherFiles = ref([]);

// 买卖双方发票文件
const invoiceFiles = ref([]);

// 让利比例选择器引用
const pointsRatioSelectorRef = ref(null);

// 让利比例列表（3% - 20%）
const pointsRatioList = ref([]);

// picker-view 的值
const pickerValue = ref([0]);

// 临时选中的让利比例值
const selectedRatioValue = ref(3);

// picker-view 的指示器样式
const indicatorStyle = "height: 50px;";

// 初始化让利比例选项（3% - 20%）
const initPointsRatioOptions = () => {
  const options = [];
  for (let i = 3; i <= 20; i++) {
    options.push(i);
  }
  pointsRatioList.value = options;
};

// 初始化比例选项
initPointsRatioOptions();

// 支付方式选择器引用
const payWaySelectorRef = ref(null);

// 支付方式列表
const payWayList = ref([
  { label: "支付宝", value: 1 },
  { label: "微信", value: 2 },
  { label: "衫德", value: 3 },
  { label: "余额", value: 4 },
  { label: "积分", value: 5 },
  { label: "汇聚(支付宝H5)", value: 10 },
  { label: "汇聚(银行卡)", value: 11 },
  { label: "汇聚(微信小程序)", value: 12 },
  { label: "汇聚(微信H5)", value: 13 },
]);

// 选中的支付方式
const selectedPayWay = ref(1); // 默认支付宝
const tempPayWay = ref(1);

// 支付方式显示文本
const payWayText = computed(() => {
  const item = payWayList.value.find(
    (item) => item.value === selectedPayWay.value,
  );
  return item ? item.label : "请选择";
});

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 显示让利比例选择器
const showPointsRatioSelector = () => {
  // 找到当前比例在选项中的索引
  const currentIndex = pointsRatioList.value.indexOf(pointsRatio.value);
  pickerValue.value = [currentIndex >= 0 ? currentIndex : 0];
  selectedRatioValue.value =
    currentIndex >= 0
      ? pointsRatioList.value[currentIndex]
      : pointsRatioList.value[0];
  pointsRatioSelectorRef.value?.open();
};

// 关闭让利比例选择器
const closePointsRatioSelector = () => {
  pointsRatioSelectorRef.value?.close();
};

// picker值改变
const pickerChange = (e) => {
  const index = e.detail.value[0];
  selectedRatioValue.value = pointsRatioList.value[index];
  pickerValue.value = [index];
};

// 确认选择让利比例
const confirmPointsRatio = () => {
  pointsRatio.value = selectedRatioValue.value;
  closePointsRatioSelector();
};

// 显示支付方式选择器
const showPayWaySelector = () => {
  tempPayWay.value = selectedPayWay.value;
  payWaySelectorRef.value?.open();
};

// 关闭支付方式选择器
const closePayWaySelector = () => {
  payWaySelectorRef.value?.close();
};

// 确认选择支付方式
const confirmPayWay = () => {
  selectedPayWay.value = tempPayWay.value;
  closePayWaySelector();
};

// 创建订单接口
const { loading: submitting, run: submitOrder } = useRequest(
  (params) => createBigReceiptOrder(params),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("创建订单成功:", response);
      uni.showToast({
        title: "订单创建成功",
        icon: "none",
      });
      // 延迟返回
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    },
    onError: (error) => {
      console.error("创建订单失败:", error);
      uni.showToast({
        title: error.message || "订单创建失败",
        icon: "none",
      });
    },
  },
);

// 提交订单
const handleSubmit = () => {
  // 防止重复提交
  if (submitting.value) {
    return;
  }

  // 验证支付金额
  if (!paymentAmount.value || parseFloat(paymentAmount.value) <= 0) {
    uni.showToast({
      title: "请输入支付金额",
      icon: "none",
    });
    return;
  }

  // 验证用户手机号
  if (!memberPhone.value) {
    uni.showToast({
      title: "请输入用户手机号",
      icon: "none",
    });
    return;
  }

  // 验证用户手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(memberPhone.value)) {
    uni.showToast({
      title: "请输入正确的用户手机号",
      icon: "none",
    });
    return;
  }

  // 验证买卖双方合同
  if (contractFiles.value.length === 0) {
    uni.showToast({
      title: "请上传买卖双方合同",
      icon: "none",
    });
    return;
  }

  // 验证买方付款凭证
  if (paymentVoucherFiles.value.length === 0) {
    uni.showToast({
      title: "请上传买方付款凭证",
      icon: "none",
    });
    return;
  }

  // 验证买卖双方发票
  if (invoiceFiles.value.length === 0) {
    uni.showToast({
      title: "请上传买卖双方发票",
      icon: "none",
    });
    return;
  }

  // 获取商户 ID
  const merchantId = Number(storeStore.storeId) || 0;
  if (!merchantId) {
    uni.showToast({
      title: "商户信息缺失",
      icon: "none",
    });
    return;
  }

  // 将图片数组转为逗号分隔的字符串
  // UploadMedia 组件返回的是对象数组，需要提取 url 字段
  const largeContract = contractFiles.value
    .map((item) => (typeof item === "string" ? item : item.url))
    .join(",");
  const largeVoucher = paymentVoucherFiles.value
    .map((item) => (typeof item === "string" ? item : item.url))
    .join(",");
  const largeInvoice = invoiceFiles.value
    .map((item) => (typeof item === "string" ? item : item.url))
    .join(",");

  // 构建接口参数
  const params = {
    amount: parseFloat(paymentAmount.value), // 支付金额
    largeContract, // 大额合同（买卖双方合同）
    largeHasInvoice: hasInvoice.value ? 1 : 0, // 大额是否有发票（1=有，0=无）
    largeInvoice, // 大额发票（买卖双方发票）
    largeVoucher, // 大额凭证（买方付款凭证）
    merchantId, // 商户id
    offerDiscountsRatio: pointsRatio.value / 100, // 让利比率（转为小数，如 3% -> 0.03）
    payWay: selectedPayWay.value, // 支付方式
    userMobile: memberPhone.value, // 用户手机号
  };

  console.log("提交订单参数:", params);
  const encryptedParams = rsa.encrypt(params, true);
  console.log("加密后的参数:", encryptedParams);

  // 调用接口
  encryptRun(encryptedParams);
  // submitOrder(params);
};
const { run: encryptRun } = useRequest(
  (params) =>
    encryptApi({
      a_d: params,
      a_m: "so_lpPay",
    }),
  {
    manual: true,
    onSuccess: (response) => {
      if (response == 2000) {
        uni.showToast({
          title: "提交成功",
          icon: "none",
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }
    },
    onError: (error) => {
      uni.showToast({ title: error.message, icon: "none" });
    },
  },
);
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content {
  padding: 20rpx 30rpx 120rpx;
}

// 表单区块
.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 32rpx;
  margin-bottom: 20rpx;

  &:first-child {
    .form-item:first-child {
      padding-top: 8rpx;
    }
  }

  &:has(.section-header, .section-header-simple) {
    padding: 32rpx;
  }

  &.upload-group {
    padding: 32rpx;
  }
}

.upload-item {
  margin-top: 40rpx;

  &:first-of-type {
    margin-top: 32rpx;
  }
}

.delivery-item {
  margin-top: 24rpx;
}

.video-upload-wrapper {
  margin-top: 24rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-header-simple {
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.required-icon {
  color: #ff4d4f;
  font-size: 28rpx;
  margin-right: 4rpx;
}

.warning-text {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-left: 8rpx;
}

.tip-description {
  margin-bottom: 24rpx;

  text {
    font-size: 24rpx;
    color: #999;
    line-height: 1.6;
  }
}

// 发货类型选择
.delivery-type {
  margin-bottom: 24rpx;
}

.radio-group {
  display: flex;
  gap: 40rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 12rpx;

  &:active {
    opacity: 0.7;
  }
}

.radio-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  .radio-item.active & {
    border-color: #fabc02;
  }
}

.radio-dot {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #fabc02;
}

.radio-label {
  font-size: 28rpx;
  color: #333;
}

// 表单项
.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 88rpx;
  padding: 0 4rpx;

  &:active:not(.input-item):not(.inline-item) {
    background-color: #f9f9f9;
  }

  &.border-bottom {
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.input-item {
  flex-direction: column;
  align-items: flex-start;
  gap: 20rpx;
}

.inline-item {
  flex-direction: row;
  align-items: center;
  gap: 20rpx;
}

.form-label-wrapper {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  white-space: nowrap;
}

.form-value {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex: 1;
  justify-content: flex-end;

  text {
    font-size: 28rpx;
    color: #333;
  }

  .placeholder {
    color: #999;
  }
}

.form-input {
  width: 100%;
  font-size: 28rpx;
  color: #333;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-input-inline {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  text-align: right;
}

.input-placeholder {
  color: #ccc;
  font-size: 28rpx;
}

.amount-input-wrapper {
  width: 100%;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 20rpx 0;
}

.amount-input-wrapper-inline {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.currency {
  font-size: 32rpx;
  color: #333;
  margin-right: 8rpx;
}

.amount-input {
  flex: 1;
  font-size: 32rpx;
  color: #333;
}

.amount-input-inline {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

// 提交按钮
.submit-button {
  width: 100%;
  height: 88rpx;
  background-color: #fabc02;
  border-radius: 50rpx;
  text-align: center;
  line-height: 88rpx;
  margin-top: 40rpx;

  text {
    font-size: 32rpx;
    color: #fff;
    font-weight: 600;
  }

  &:active:not(.disabled) {
    opacity: 0.8;
  }

  &.disabled {
    opacity: 0.6;
    pointer-events: none;
  }
}

// 比例选择器
.ratio-picker-modal {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.picker-cancel {
  font-size: 28rpx;
  color: #666;

  &:active {
    opacity: 0.6;
  }
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.picker-confirm {
  font-size: 28rpx;
  color: #fabc02;

  &:active {
    opacity: 0.6;
  }
}

.picker-view {
  height: 400rpx;
  padding: 0 32rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  line-height: 50px;
  font-size: 32rpx;
  color: #333;
}

// 支付方式选择器
.pay-way-selector {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.selector-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.selector-cancel,
.selector-confirm {
  font-size: 28rpx;
  color: #666;

  &:active {
    opacity: 0.6;
  }
}

.selector-confirm {
  color: #fabc02;
}

.selector-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.pay-way-list {
  max-height: 600rpx;
}

.pay-way-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &:active {
    background-color: #f9f9f9;
  }

  &.active {
    background-color: #fffbf0;

    .pay-way-name {
      color: #fabc02;
      font-weight: 600;
    }
  }
}

.pay-way-name {
  font-size: 28rpx;
  color: #333;
}
</style>
